package com.lyx.db137.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lyx.db137.common.JwtUtils;
import com.lyx.db137.common.R;
import com.lyx.db137.entity.Menu;
import com.lyx.db137.entity.User;
import com.lyx.db137.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * @Author: zero domain
 * @CreateTime: 2024/12/24 11:50
 * @Description: TODO
 * @Version: 1.0
 */

/**
 * user相关
 */
@CrossOrigin(origins = "*")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据当前用户返回用户的菜单集合数据
     * @return
     */
    @GetMapping("/selectUserMenu")
    public R selectUserMenu(@RequestHeader("token")String token) {
        System.out.println(token);
        //解析token，获取用户信息
        Integer userid= JwtUtils.getJwtToken(token,"userid");
//        int userid=1;
        List<Menu> menuList= this.userService.selectUserMenuByUserId(userid);
        return new R().add("menuList",menuList);
    }

    @RequestMapping("userlogin")
    public R userlogin(@RequestBody String uname,String upwd){
        return new R().add("user",this.userService.userlogin(uname,upwd));
    }
    @PostMapping("userregister")
    public R login(@RequestBody User user){
        QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
        userQueryWrapper.setEntity(user);
        User one = this.userService.getOne(userQueryWrapper);
        if(one!=null){//登录成功
            //生成token JWT
            HashMap<String, Object> map = new HashMap<>();
//            one.setUpwd("");
//            map.put("user",one);
            map.put("userid",one.getId());
            String jwtToken= JwtUtils.createJwtToken(map);
            System.out.println(jwtToken);
            return new R().add("token",jwtToken);
        }//登录失败
        return new R().setMessage("登录出差了").setCode(500);
    }

    @RequestMapping("userregister")
    public R register(@RequestBody User user){
        return new R().add("user",this.userService.register(user));
    }

    @GetMapping("selectAll")
    public R selectAll(){
        return new R().add("userList",this.userService.selectAll());
    }

    @PostMapping("insert")
    public R insert(@RequestBody User user){
        return new R().add("user",this.userService.insert(user));
    }
    @PostMapping("update")
    public R update(@RequestBody User user){
        return new R().add("user",this.userService.update(user));
    }
    @PostMapping("delete/{id}")
    public R delete(@PathVariable("id")int id){
        return new R().add("user",this.userService.delete(id));
    }
    @GetMapping("selectUser")
    public R selectUser(){
        List<User> userList=this.userService.list();
        return new R().add("userList",userList);
    }
}
